<?php
//require_once  __DIR__ . '/includes/authenticate.php';

if (isset($_POST['teamname']) && $_POST['teamname'] != '' ) {

	require_once __DIR__ . '/db_connect_basketbal.php';

	$teamname = $_POST['teamname'];

	// check if teamname already exists
	$sql = "SELECT COUNT(*) FROM teams_list WHERE teamname = :teamname";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':teamname', $teamname);
	$stmt->execute();

	if ($stmt->fetchColumn() != 0) {
		echo "$teamname already exists, choose another teamname.";
	} else {
		try {	
				//Create new user in DB
				$teamID = hash('crc32', microtime(true). mt_rand().$teamname);
				$sql = "INSERT INTO teams_list (teamID, teamname) VALUES (:teamID,:teamname)";
				$stmt = $db->prepare($sql);
				$stmt->bindParam(':teamID', $teamID);
				$stmt->bindParam(':teamname', $teamname);
				$stmt->execute();
				} catch (\PDOException $e){
					if (0 === strpos($e->getCode(),'23')) {
						$teamID = hash('crc32', microtime(true). mt_rand().$teamname);
						if (!$stmt->execute()) {
							throw $e;
						}
					}
				}
				if ($stmt->rowCount()) {
					echo "Team $teamname successfully added";

					exit;
				}
		}
	} elseif ($_POST['teamname'] == ''){
		echo "No teamname entered";
	}


?>

